package com.hhkj.study.common.logic;

import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * Jackson 实现 List< Long> 字段类型处理器
 * 用com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler  如何json里面包括List<Long>属性，
 * 该字段将会出现 java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long 异常
 *
 * @author hanhan666666
 * @since 2024-3-28
 */
@Slf4j
@MappedTypes({Object.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
@AllArgsConstructor
@Component
public class ListLongJacksonHandler extends AbstractJsonTypeHandler<Object> {
    private final ObjectMapper objectMapper;
    @Override
    protected Object parse(String json) {
        try {
            return objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, Long.class));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
